package dao

import models._
import models.Status._

//Db4o implementation
import com.db4o.ObjectContainer
import com.db4o.query.Query

object CommentDAO extends CommonDAO[Comment] {
  import scala.collection.JavaConversions._
  
  def createAndRef(author:User, post:Post, created:java.util.Date, content:String, status:Status)
                  (implicit s:Session):Option[Comment] = {
    val c:Comment = new Comment(author, post, created, content, status)
    if(save(c)){
      Some(c)
    } else {
      None
    }
  }
  
  def findByUser(u:User)(implicit s:Session) :Option[List[Comment]] = {
    val query:Query = s.get.query()
    query.constrain(classOf[Comment])
    query.descend("author").constrain(u)
    val result:List[Comment] = query.execute().toList
    if(!result.isEmpty){
      Some(result)
    } else {
      None 
    }
  }
  def findByPost(p:Post)(implicit s:Session):Option[List[Comment]] = {
    val query:Query = s.get.query()
    query.constrain(classOf[Comment])
    query.descend("post").constrain(p)
    val result:List[Comment] = query.execute().toList
    if(!result.isEmpty){
      Some(result)
    } else {
      None 
    }
  }
  
  def findByID(id:Long)(implicit s:Session):Option[Comment] = {
    try{
      val c:Comment = s.get.ext().getByID(id)
      if(c != null){
        Some(c)
      } else {
        None
      }
    } catch {
      case ex:Exception => None
    }
  }
  
  def getID(c:Comment)(implicit s:Session):Long = {
    s.get.ext().getID(c)
  }
  
}